package com.smbms.users.controller;

import com.github.pagehelper.PageInfo;
import com.smbms.commons.bean.Users;
import com.smbms.commons.config.JsonResult;
import com.smbms.commons.config.JwtConfig;
import com.smbms.commons.config.ResultCode;
import com.smbms.commons.config.ResultTool;
import com.smbms.commons.service.UsersService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/user")
public class UsersController {
    @Resource
    private UsersService usersService;

    @PostMapping("/login")
    public JsonResult<String> login(Users user) {
        return usersService.login(user);
    }

    @GetMapping("/a")
    public JsonResult<String> a(HttpServletRequest request) {
        boolean b = JwtConfig.checkToken(request);
        if (!b) {
            return ResultTool.fail(ResultCode.USER_NOT_LOGIN);
        }
        return ResultTool.success("欢迎访问!");
    }

    @GetMapping("/find")
    public JsonResult<PageInfo<Users>> find(@RequestParam(name = "page", defaultValue = "1") Integer page) {
        return usersService.findAllUsers(page);
    }

    @GetMapping("/search")
    public JsonResult<PageInfo<Users>> find(@RequestParam(name = "page", defaultValue = "1") Integer page, String name, Integer role) {
        return usersService.findUserByNameAndRoleName(name, role, page);
    }

    @PostMapping("/save")
    public String save(Users user) {
        boolean b = usersService.save(user);
        if (!b) {
            return "not save";
        }
        return "save ok!";
    }

    @DeleteMapping("/remove")
    public String remove(Integer id) {
        boolean b = usersService.removeById(id);
        if (!b) {
            return "not remove";
        }
        return "remove ok!";
    }
}
